#!/usr/bin/env python
'''
This script gets all *.xml files from /var/lib/jenkins and backs them up into the config repo of GIT.
'''
import logging
import os
import re
import shutil
import sys
from argparse import ArgumentParser

from git import Repo

'''
CONFIGURE LOG LEVEL
'''
logging.basicConfig(level=logging.INFO)

'''
PARSE CMD LINE ARGS
'''
argparser = ArgumentParser(description='Args for doing jenkins backup.')
argparser.add_argument('--platform', help="Which Jenkins are you backing up? [andr|ios]", required=True)
args = argparser.parse_args()
if re.search("^andr$", args.platform) or re.search("^ios$", args.platform):
    platform = args.platform
else:
    logging.exception(args.platform + " is invalid. --platform must be andr or ios")
    sys.exit(1)

'''
SET STATIC VARIABLES
'''
GIT_BRANCH = "master"
BACKUP_REPO = "config"
JENKINS_HOME = "/var/lib/jenkins"
JENKINS_JOBS_HOME = os.path.join(JENKINS_HOME, "jobs")
BACKUP_PATH = os.path.join(os.environ['WORKSPACE'], BACKUP_REPO, "jenkins", platform)
BACKUP_JOBS_PATH = os.path.join(BACKUP_PATH, "jobs")

# COPY CONFIG FILES TO REPO
active_jobs = os.listdir(JENKINS_JOBS_HOME)

if not os.path.isdir(BACKUP_PATH):
    os.makedirs(BACKUP_PATH)
os.chdir(BACKUP_PATH)
for a_file in os.listdir(JENKINS_HOME):
    if a_file.endswith('.xml'):
        shutil.copyfile(os.path.join(JENKINS_HOME, a_file), os.path.join(BACKUP_PATH, a_file))
# pdb.set_trace()
# os.system("pwd")
# http://www.clausconrad.com/blog/backup-jenkins-configuration-to-s3      
print "rsync -av --exclude='jobConfigHistory'  --delete --exclude='workspace*'   --exclude='war' --exclude='config-history'     --exclude='.hudson'     --exclude='.ivy2'     --exclude='.m2'     --exclude='lost+found'     --include='*/'  --include='*config.xml'     --include='users/*'     --include='*.hpi'     --include='*.jpi'     --include='*pinned'     --include='*disabled'  --exclude='*'  --prune-empty-dirs  " + JENKINS_HOME + "  " + BACKUP_PATH
os.system(
    "rsync -av --exclude='jobConfigHistory' --delete  --exclude='workspace*'   --exclude='war' --exclude='config-history'     --exclude='.hudson'     --exclude='.ivy2'     --exclude='.m2'     --exclude='lost+found'     --include='*/'  --include='*config.xml'     --include='users/*'     --include='*.hpi'     --include='*.jpi'     --include='*pinned'     --include='*disabled'  --exclude='*'  --prune-empty-dirs  " + JENKINS_HOME + "  " + BACKUP_PATH)
# SETUP GIT COMMUNICATION
# print("REPO = " + os.environ['WORKSPACE'], BACKUP_REPO)
git_repo = Repo(os.path.join(os.environ['WORKSPACE'], BACKUP_REPO))
print "---------------"
# print git_repo.git.branch('--set-upstream', "origin/" + GIT_BRANCH, GIT_BRANCH)
print "---------------"
print git_repo.remotes.origin.pull()
print "---------------"
print git_repo.git.status()
print "---------------"
git_repo.git.add("jenkins")
git_repo.git.config('--global', "user.name", "builder")
git_repo.git.config('--global', "user.email", "builder@ebay.com")
# DELETE ITEMS FROM GIT WHICH NEED REMOVED
for d in os.listdir(BACKUP_PATH + "/jenkins/jobs"):
    if not d in active_jobs:

        to_rm = os.path.join(BACKUP_PATH, d)
        print git_repo.git.rm('-rf', to_rm)
    else:
        git_repo.git.add('.')
print os.getcwd()
print git_repo.git.status()
# COMMIT CHANGES
if not re.search("nothing to commit", git_repo.git.status()):
    print "---------------"
    # pdb.set_trace()
    deleted_list = git_repo.git.ls_files('--deleted')
    for line in deleted_list.split('\n'):
        if line:
            print "DELETE '" + line + "'"
            git_repo.git.rm(line)
    # git ls-files --deleted -z | xargs -0 git rm
    print "---------------"
    print git_repo.git.commit(m=" " + os.environ["BUILD_TAG"])
    print "---------------"
    print git_repo.git.push('--set-upstream', 'origin', GIT_BRANCH)
    print "---------------"

# https://github.corp.ebay.com/DEVOPS/scripts/blob/develop/jenkins_backup.py